package pdfsetter.core.schema.selectors;

import java.util.Iterator;

import pdfsetter.core.schema.advanced.FilePageSelection;
import pdfsetter.core.schema.advanced.FilePageSelector;
import pdfsetter.core.util.RandomAccessIterableIterator;

/**
 * One of basic selectors - we take every leap-th page from file.
 * 
 * @author Andrzej Dorobisz
 */
public class LeapingPageSelector implements FilePageSelector {
    private final int leap;

    public LeapingPageSelector(int leap) {
        this.leap = leap;
    }

    @Override
    public FilePageSelection selectPages(int fileSize) {
        return new LeapedPageSelection(fileSize);
    }

    private class LeapedPageSelection implements FilePageSelection {
        private final int size;

        public LeapedPageSelection(int fileSize) {
            if (fileSize == 0)
                size = 0;
            else
                size = 1 + (fileSize - 1) / leap;
        }

        @Override
        public Integer get(int index) {
            if (index >= size || index < 0)
                throw new IndexOutOfBoundsException();
            return index * leap;
        }

        @Override
        public int size() {
            return size;
        }

        @Override
        public Iterator<Integer> iterator() {
            return new RandomAccessIterableIterator<Integer>(this);
        }

    }

}
